
package com.intelligent.mts.da.codec;


import com.intelligent.mts.da.xmlmessage.Validate;
import com.intelligent.mts.da.utils.JaxbUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.io.StringReader;
import java.nio.charset.Charset;


public abstract class AbstractHttpXmlDecoder<T> extends
        MessageToMessageDecoder<T> {

    //    private IBindingFactory factory;
    private StringReader reader;
    private Class<?> clazz;
    private boolean isPrint;
    private final static String CHARSET_NAME = "UTF-8";
    private final static Charset UTF_8 = Charset.forName(CHARSET_NAME);

    protected AbstractHttpXmlDecoder(Class<?> clazz) {
        this(clazz, false);
    }

    protected AbstractHttpXmlDecoder(Class<?> clazz, boolean isPrint) {
        this.clazz = clazz;
        this.isPrint = isPrint;
    }

    protected Object decode0(ChannelHandlerContext ctx, ByteBuf body)
            throws Exception {

        String content = body.toString(UTF_8);

        content = content.trim();

        if ("WSDL".equalsIgnoreCase(content)){
            return "WSDL";
        }

        Validate validate = JaxbUtil.converyToJavaBean(content, Validate.class);



        return validate;
    }

    /**
     * Calls {@link ChannelHandlerContext#fireExceptionCaught(Throwable)} to
     * forward to the next {@link ChannelHandler} in the {@link ChannelPipeline}
     * .
     *
     * Sub-classes may override this method to change behavior.
     */
//    @Skip
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        // 释放资源
        if (reader != null) {
            reader.close();
            reader = null;
        }
    }
}
